import { Component, OnInit, Input, SimpleChanges } from '@angular/core';
import { Software } from '../../services/zone.service';
import { MySelection } from 'app/modules/base/selection';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { SoftwareService } from 'app/modules/software/services/software.service';
import { ArrayAPIBase } from 'app/modules/base/api-base';
import { map, startWith } from 'rxjs/operators';
import { ReplaySubject } from 'rxjs/internal/ReplaySubject';

@Component({
  selector: 'm-pre-install',
  templateUrl: './pre-install.component.html',
  styleUrls: ['./pre-install.component.scss'],
  providers: [
    {
      multi: true,
      provide: NG_VALUE_ACCESSOR,
      useExisting: PreInstallComponent,
    },
  ],
})
export class PreInstallComponent<T extends { app_id: number }> implements OnInit, ControlValueAccessor {
  constructor(private software: SoftwareService, private route: ActivatedRoute) {}

  @Input() dataList;
  @Input() editing;
  dataSource: ArrayAPIBase<T>;
  values$ = new ReplaySubject<Software[]>(1);
  selection = new MySelection<Software>('app_id');

  selectedService$ = this.selection.change.pipe(
    startWith(this.selection.selected),
    map(() => {
      const selectedItems = this.selection.selected;
      const datasource = new ArrayAPIBase(selectedItems);
      datasource.search = this.searchList;
      selectedItems.sort((prevItem, nextItem) => {
        return prevItem.app_id - nextItem.app_id;
      });
      this.values$.next(selectedItems);
      return datasource;
    }),
  );

  ngOnInit() {
    let r = this.route;
    while (r.firstChild) {
      r = r.firstChild;
    }
    this.dataSource = new ArrayAPIBase(this.dataList);
    this.dataSource.search = this.searchList;
  }

  ngOnChanges(changes: SimpleChanges) {
    for (let propName in changes) {
      if (propName === 'dataList') {
        let chng = changes[propName];
        this.dataSource = new ArrayAPIBase(chng.currentValue);
        this.dataSource.search = this.searchList;
      }
    }
  }
  searchList(obj: any, keyword: string) {
    keyword.toLowerCase();
    if (obj.title && obj.title.toLowerCase().includes(keyword)) {
      return true;
    }
    return false;
  }

  writeValue(data: Software[]): void {
    this.selection.clear();
    //默认选中
    data.forEach((item) => {
      if (item.whether_clip === 0) {
        this.selection.select(item);
      } else {
        this.selection.unselect(item);
      }
    });
  }

  registerOnChange(fn: any): void {
    this.values$.subscribe(fn);
  }

  registerOnTouched(fn: any): void {

  }

  setDisabledState?(isDisabled: boolean): void {

  }
}
